package com.wlr.blog.job;

import org.quartz.*;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;

/**
 * @author lrwang
 * @version 1.0
 * @date 2022/11/22 13:01
 */
public class ScheduleUtils {
    public static final String QUARTZ_NAME = "QUARTZ_NAME";

    public static JobKey getJobKey(Long jobId, String jobGroup) {
        return JobKey.jobKey(QUARTZ_NAME + jobId, jobGroup);
    }

    public static Scheduler createScheduleJob(SysJob job) throws SchedulerException {
        Class<QuartzJobExecution> quartzJobExecutionClass = QuartzJobExecution.class;
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(quartzJobExecutionClass)
                .withIdentity(getJobKey(jobId, jobGroup))
                .build();
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        jobDetail.getJobDataMap().put("key", job);
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(getTriggerKey(jobId, jobGroup))
                .withSchedule(cronScheduleBuilder).build();
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(jobDetail, trigger);
        return scheduler;
    }

    public static void startScheduleJob(Scheduler scheduler) throws SchedulerException {
        scheduler.start();
    }

    private static TriggerKey getTriggerKey(Long jobId, String jobGroup) {
        return TriggerKey.triggerKey(QUARTZ_NAME + jobId, jobGroup);
    }
}
